<template>
  <BasicDrawer
    :title="getTitle"
    showFooter
    v-bind="$attrs"
    width="50%"
    @ok="handleSubmit"
    @register="registerDrawer"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { FormSchemaAdd } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { doMenuAdd, getMenuParentList } from '../api';
  import { useMessage } from '@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('0');
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 90,
        schemas: FormSchemaAdd,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        const treeData = await getMenuParentList();
        await updateSchema({
          field: 'pid',
          componentProps: { treeData },
        });
        //修改
        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          await setFieldsValue({
            ...data.record,
          });
        } else {
          rowId.value = '0';
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));
      const { createMessage } = useMessage();

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          doMenuAdd({ ...values, id: rowId.value }).then((res) => {
            if (res.code > 0) {
              createMessage.error(res.message);
              return;
            }
            createMessage.success(res.message);
            closeDrawer();
            emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
          });
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
